﻿using CommunityToolkit.Mvvm.Input;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using UpperComputer.Application;
using UpperComputer.WPF.Entry.Common;

namespace UpperComputer.WPF.Entry.ViewModels
{
    public class LoginViewModel : BaseViewModel
    {
        private readonly IAuthorizeService _authorizeService;

        public LoginBaseDto Login { get; } = new LoginBaseDto();

        public IAsyncRelayCommand<Window> LoginCommand { get; }

        public IRelayCommand LanguageSelectCommand { get; }

        public LoginViewModel(IAuthorizeService authorizeService)
        {
            _authorizeService = authorizeService;
            SetLang();
            LoginCommand = new AsyncRelayCommand<Window>(LoginCommand_Execute, window => !LoginCommand.IsRunning);
            LanguageSelectCommand = new RelayCommand(() => SetLang());
        }

        private async Task LoginCommand_Execute(Window window, CancellationToken cancellationToken)
        {
            if (!Login.IsValidated)
            {
                return;
            }
            await TryExecuteCommandAysnc(async cancellationToken =>
            {
                BaseUserResultDto user = await _authorizeService.LoginWithNoVerificationCode(Login, cancellationToken);
                YSession.SubjectId = user.Id;
                YSession.Account = user.Account;
                YSession.UserName = user.DisplayName;
                window.DialogResult = true;
                window.Close();
            }, cancellationToken);
        }
    }
}
